package edu.seu.mart.controller;

import edu.seu.mart.entity.Pager;
import edu.seu.mart.model.*;
import edu.seu.mart.service.*;
import edu.seu.mart.web.SessionContext;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * Created by asus on 2015/3/24.
 */
@Controller
@RequestMapping("/seller")
public class SellerController {

    @Resource
    private IGoodsService goodsService;

    @Resource
    private IOrderService orderService;

    @Resource
    private ISellerService sellerService;

    @Resource
    private IUserService userService;

    private String imagestr = "";
    private String fourImagestr = "";
    private String detailImagestr = "";

    @RequestMapping("/index")
    public String index() {
        return "seller/index";
    }

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login() {
        return "seller/login";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(String username, String password, HttpSession session) throws NoSuchAlgorithmException {
        Seller seller = sellerService.login(username, password);
        if (seller != null) {
            session.setAttribute("seller", seller);
            SessionContext.addSessoin(session);
            System.out.println(session.getId());
            return "redirect:/seller/index";
        } else {
            return "redirect:/seller/login";
        }

    }

    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("seller");
        session.invalidate();
        return "seller/login";
    }

    /**
     * 商品管理
     *
     * @param model
     * @param request
     * @param session
     * @return
     */
    @RequestMapping("/goodsList")
    public String goodsList(Model model, HttpServletRequest request, HttpSession session) {
        String status = request.getParameter("status");
        if (status != null && !"".equals(status.trim())) {
            int id = ((Seller) session.getAttribute("seller")).getId();
            Pager<Goods> goodsList = goodsService.findGoodsListBySellerId(id, status);
            model.addAttribute("goodsList", goodsList);
        } else {
            model.addAttribute("goodsList", goodsService.findGoodsListBySellerId(((Seller) request.getSession().getAttribute("seller")).getId(), null));
        }
        return "seller/goodsList";
    }

    @RequestMapping(value = "/goods/{id}/delete", method = RequestMethod.GET)
    public String goodsDelete(@PathVariable int id) {
        goodsService.delete(id);
        return "redirect:/seller/goodsList?status=1";
    }

    @RequestMapping(value = "/goods/add", method = RequestMethod.GET)
    public String goodsAdd(@ModelAttribute("goods") Goods goods) {
        return "seller/add";
    }

    @RequestMapping(value = "/goods/add", method = RequestMethod.POST)
    public String goodsAdd(Goods goods, HttpServletRequest request) throws IOException {
        goods.setImage(imagestr);
        goods.setFourImage(fourImagestr);
        goods.setDetailImage(detailImagestr);
        goods.setStatus(0);
        goods.setSeller((Seller) request.getSession().getAttribute("seller"));
        goods.setSalesnum(0);
        goods.setUptime(new Date());
        goodsService.add(goods);
        return "redirect:/seller/goodsList?status=1";
    }

    @RequestMapping(value = "/goods/{id}/update", method = RequestMethod.GET)
    public String goodsUpdate(@PathVariable int id, Model model) {
        model.addAttribute(goodsService.load(id));
        return "seller/update";
    }

    @RequestMapping(value = "/goods/{id}/update", method = RequestMethod.POST)
    public String goodsUpdate(@PathVariable int id, @Validated Goods goods, BindingResult br, HttpServletRequest request) throws IOException {
        if (br.hasErrors()) {
            return "redirect:/seller/goodsList?status=1";
        }
        Goods oldGoods = goodsService.load(goods.getId());
        if (imagestr != "" && imagestr != null) {
            oldGoods.setImage(imagestr);
        }
        if (fourImagestr != "" && fourImagestr != null) {
            oldGoods.setFourImage(fourImagestr);
        }
        if (detailImagestr != "" && detailImagestr != null) {
            oldGoods.setDetailImage(detailImagestr);
        }
        oldGoods.setName(goods.getName());
        oldGoods.setBrand(goods.getBrand());
        oldGoods.setCPU(goods.getCPU());
        oldGoods.setRAM(goods.getRAM());
        oldGoods.setHD(goods.getHD());
        oldGoods.setGraphic(goods.getGraphic());
        oldGoods.setPrice(goods.getPrice());
        oldGoods.setDescriber(goods.getDescriber());

        goodsService.update(oldGoods);
        return "redirect:/seller/goodsList?status=1";
    }

    @RequestMapping(value = "/goods/{id}/updateStatus/{flag}", method = RequestMethod.GET)
    public String goodsUpdateStatus(@PathVariable int id, @PathVariable int flag) throws IOException {
        if (flag == 2) {
            goodsService.delete(id);
        } else {
            goodsService.updateStatus(id);
        }

        return "redirect:/seller/goodsList?status=1";
    }

    @RequestMapping(value = "/deleteGoodsChecked", method = RequestMethod.POST)
    public String deleteGoodsChecked(@RequestParam("ids") String[] ids) {
        goodsService.delete(ids);

        return "redirect:/seller/goodsList?status=1";
    }

    @RequestMapping(value = "/goods/backSearch", method = RequestMethod.POST)
    public String goodsSearch(@RequestParam("name") String name, Model model) {
        model.addAttribute("goodsList", goodsService.findGoods(name));
        return "seller/goodsList";
    }


    @RequestMapping(value = "/uploadImage", method = RequestMethod.POST)//返回的是json类型的值，而uploadify只能接受字符串
    public void uploadImage(MultipartFile image, HttpServletResponse resp, HttpServletRequest request) throws IOException {
        resp.setContentType("text/plain;charset=utf-8");
        if (image != null) {
            String realPath = request.getSession().getServletContext().getRealPath("/resources/images/goodsImages");
            UUID uuid = UUID.randomUUID();
            String path = realPath + "/" + uuid;
            File localFile = new File(path);
            image.transferTo(localFile);
            imagestr = uuid.toString();
            resp.getWriter().write("上传成功");
        }
    }

    @RequestMapping(value = "/uploadFourImage", method = RequestMethod.POST)//返回的是json类型的值，而uploadify只能接受字符串
    public void uploadFourImage(MultipartFile fourimage, HttpServletResponse resp, HttpServletRequest request) throws IOException {
        if (fourimage != null) {
            resp.setContentType("text/plain;charset=utf-8");
            String realPath = request.getSession().getServletContext().getRealPath("/resources/images/goodsImages");
            UUID uuid = UUID.randomUUID();
            String path = realPath + "/" + uuid;
            File localFile = new File(path);
            fourimage.transferTo(localFile);
            fourImagestr += uuid.toString() + ";";
            resp.getWriter().write("上传成功");
        }

    }

    @RequestMapping(value = "/uploadDetailImage", method = RequestMethod.POST)//返回的是json类型的值，而uploadify只能接受字符串
    public void uploadDetailImage(MultipartFile detailimage, HttpServletResponse resp, HttpServletRequest request) throws IOException {
        resp.setContentType("text/plain;charset=utf-8");
        if (detailimage != null) {
            resp.setContentType("text/plain;charset=utf-8");
            String realPath = request.getSession().getServletContext().getRealPath("/resources/images/goodsImages");
            UUID uuid = UUID.randomUUID();
            String path = realPath + "/" + uuid;
            File localFile = new File(path);
            detailimage.transferTo(localFile);
            detailImagestr += uuid.toString() + ";";
            resp.getWriter().write("上传成功");
        }
    }

    /**
     * 订单管理
     */
    @RequestMapping("/orderList")
    public String orderList(Model model, HttpServletRequest req, HttpSession session) {
        String state = req.getParameter("state");
        Seller seller = (Seller) session.getAttribute("seller");
        if (seller == null) {
            return "redirect:/seller/login";
        }
        System.out.println("state:" + state);
        if (state == null) {
            model.addAttribute("orderList", orderService.loadBySellerId(seller.getId()));
        } else if (state.equals("已完成")) {
            model.addAttribute("orderList", orderService.findByState(seller.getId(), "已完成", "已评价"));

        } else {
            model.addAttribute("orderList", orderService.findBySellState(seller.getId(), state));
        }
        return "seller/orderList";
    }


    @RequestMapping(value = "/{id}/update", method = RequestMethod.GET)
    public String orderUpdate(@PathVariable int id, Model model) {
        model.addAttribute("order", orderService.load(id));
        return "seller/orderUpdate";
    }

    @RequestMapping(value = "/{id}/update", method = RequestMethod.POST)
    public String orderUpdate(@PathVariable int id, String state, Double total) {
        if (state.equals("退款成功")) {
            System.out.println("退款成功");
            int userId = orderService.load(id).getUser_id();
            User user = userService.load(userId);
            total = total + user.getMoney();
            userService.updateMoney(userId, total);
        }
        orderService.update(id, state, total);
        return "redirect:/seller/orderList";
    }

    @RequestMapping(value = "/{id}/detail", method = RequestMethod.GET)
    public void orderDetail(@PathVariable int id, Model model) {
        Order order = orderService.load(id);
        model.addAttribute("order", order);
        model.addAttribute("seller", sellerService.load(order.getSeller_id()));
    }

    @RequestMapping(value = "/search", method = RequestMethod.POST)
    public String orderSearch(@RequestParam int orderId, Model model) {
        model.addAttribute("orderList", orderService.load(orderId));
        return "/seller/orderList";
    }

    @RequestMapping(value = "/goodsDetail/{id}", method = RequestMethod.GET)
    public String goodsDetail(@PathVariable int id, Model model) {
        Goods goods = goodsService.load(id);
        model.addAttribute("goods", goods);
        List<String> fourImageList = new ArrayList<String>();
        String fourImageStr = goods.getFourImage();
        if (fourImageStr != null) {
            Collections.addAll(fourImageList, fourImageStr.split(";"));
        }
        List<String> detailImageList = new ArrayList<String>();
        String detailImageStr = goods.getDetailImage();
        if (detailImageStr != null) {
            Collections.addAll(detailImageList, detailImageStr.split(";"));
        }
        model.addAttribute("fourImageList", fourImageList);
        model.addAttribute("detailImageList", detailImageList);
        return "/seller/goodsDetail";
    }


    /**
     * 销售统计
     */
    @RequestMapping(value = "/monthStatistics")
    public String monthStatistics() {
        return "seller/monthStatistics";
    }

    @RequestMapping(value = "/yearStatistics")
    public String yearStatistics() {
        return "seller/yearStatistics";
    }

    @RequestMapping(value = "/monthSta", produces = MediaType.APPLICATION_JSON_VALUE)
    public
    @ResponseBody
    MonthStaJson monthSta(HttpSession session) throws IOException {

        MonthStaJson monthstaJson = new MonthStaJson();

        Calendar firstDay = Calendar.getInstance();
        firstDay.set(Calendar.DAY_OF_MONTH, 1);
        Calendar currentDay = Calendar.getInstance();
        while (!firstDay.after(currentDay)) {
            monthstaJson.day.add((firstDay.getTime().getMonth() + 1) + "/" + (firstDay.getTime().getDate()));
            Double dou = orderService.getMoneyOfOneDayBySeller(firstDay.getTime(), ((Seller) session.getAttribute("seller")).getId());
            if (dou == null) {
                monthstaJson.moneyList.add(0.0);
            } else {
                monthstaJson.moneyList.add(dou);
                monthstaJson.total += dou;
            }
            firstDay.add(Calendar.DAY_OF_MONTH, 1);
        }
        return monthstaJson;
    }

    @RequestMapping(value = "/yearSta", produces = MediaType.APPLICATION_JSON_VALUE)
    public
    @ResponseBody
    MonthStaJson yearSta(HttpSession session) throws IOException {

        MonthStaJson monthstaJson = new MonthStaJson();

        Calendar currentDay = Calendar.getInstance();
        int year = currentDay.get(Calendar.YEAR);
        int month = currentDay.getTime().getMonth() + 1;
        for (int i = 1; i <= month; i++) {
            monthstaJson.day.add(year + "-" + i);
            Double dou = orderService.getMoneyOfOneMonthBySeller(year, i, ((Seller) session.getAttribute("seller")).getId());
            if (dou == null) {
                monthstaJson.moneyList.add(0.0);
            } else {
                monthstaJson.moneyList.add(dou);
                monthstaJson.total += dou;
            }
        }
        return monthstaJson;
    }

    class MonthStaJson {
        public double total;
        public List<String> day = new ArrayList<String>() {};
        public List<Double> moneyList = new ArrayList<Double>() {};
    }

}
